const jwt = require('jsonwebtoken')
const { redisClient } = require('../config/db')

// 验证 Token 中间件
const authenticateToken = async (ctx, next) => {
	const authHeader = ctx.headers.authorization
	const accessToken = authHeader && authHeader.split(' ')[1] // Bearer TOKEN

	if (!accessToken) {
		// ctx.status = 401
		ctx.body = { code: 401, data: null, msg: '访问令牌不存在！' }
		return
	}

	try {
		// 检查 Redis 中是否存在此 accessToken（用于实现登出功能）
		const inBlacklist = await redisClient.get(`blacklist:${accessToken}`)
		if (inBlacklist) {
			// ctx.status = 401
			ctx.body = { code: 401, data: null, msg: '令牌已失效！' }
			return
		}

		// 验证 accessToken
		const decoded = jwt.verify(accessToken, process.env.JWT_SECRET || 'your-secret-key')
		ctx.state.user = decoded
		await next()
	} catch (err) {
		// ctx.status = 401
		ctx.body = { code: 401, data: null, msg: '令牌无效或已过期！' }
	}
}

module.exports = { authenticateToken }
